package com.shunova.core.dao.mongo;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.mongodb.WriteResult;
import com.shunova.core.entity.mongo.Notice;

@Component
public class UserDao {

	@Autowired
	protected MongoOperations mongoOperations;

	public String save(int siteId, String creator, Notice notice) {
		Date now = new Date();
		notice.setSiteId(siteId);
		notice.setCreator(creator);
		notice.setCreateTime(now);
		notice.setUpdateTime(now);
		mongoOperations.insert(notice);
		return notice.getId();
	}

	public int update(/*int siteId, */String id, Notice notice) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(id)/*.and("siteId").is(siteId)*/);
		Update update = new Update();
		update.set("title", notice.getTitle());
		update.set("content", notice.getContent());
		update.set("updateTime", new Date());
		WriteResult result = mongoOperations.updateFirst(query, update, Notice.class);
		return result.getN();
	}

	/*public Pager page(Pager pager, int siteId, NoticeSearchParams searchParams) {
		Query query = new Query();
		query.addCriteria(Criteria.where("siteId").is(siteId));
		if (!StringTool.isNullOrEmpty(searchParams.getTitleKey())) {
			query.addCriteria(Criteria.where("title").regex(searchParams.getTitleKey(), "i"));
		}
		if (searchParams.getSortMode() == NoticeSearchParams.SORT_MODE_CREATE_TIME_DESC) {
			query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")));
		}
		int skipCount = (pager.getPageNo() > 0 ? pager.getPageNo() - 1 : 0) * pager.getPageSize();
		query.skip(skipCount);
		query.limit(pager.getPageSize());
		List<Notice> notices = mongoOperations.find(query, Notice.class);
		pager.setResult(notices);
		return pager;
	}*/

	public Notice get(String id) {
		CriteriaDefinition criteria = Criteria.where("id").is(id)/*.and("siteId").is(siteId)*/;
		Query queryExam = Query.query(criteria);
		Notice notice = mongoOperations.findOne(queryExam,
				Notice.class);
		return notice;
	}

	public void remove(/*int siteId,*/ String id) {
		mongoOperations.remove(Query.query(Criteria.where("id").is(id)/*.and("siteId").is(siteId)*/), Notice.class);
	}

}
